<script src="../../router/index.js"></script>
<template>
  <div class="wrapper">
    <h1>websocketDemo 测试页面</h1>
    <p>【userId】：<div><input id="userId" type="text" v-model="userId"></div>
    <p>【toUserId】：<div><input id="toUserId" type="text" v-model="toUserId"></div>
    <p>【toUserId】：<div><input id="contentText" type="text" v-model="contentText"></div>
    <p>【receive msg】：<div class="receiveMsgDiv" style="text-align:center;width:100%;height:40px;">{{receiveMsg}}</div>
    <p>【操作】：<div><a href="javascript:;" @click="openSocket()">开启socket</a></div>
    <p>【操作】：<div><a href="javascript:;" @click="sendMessage()">发送消息</a></div>
  </div>
</template>

<script>
  export default {
    components: {},
    props: {},
    data () {
      return {
        socket: undefined,
        userId: '999',
        toUserId: '20',
        contentText: 'hello websocket',
        receiveMsg: ''
      }
    },
    watch: {},
    computed: {},
    created () {},
    mounted () {
    },
    methods: {
      openSocket () {
        console.log(this.socket)
        if (typeof (WebSocket) === 'undefined') {
          console.log('your browser not support websocket')
        } else {
          console.log('your bowser support websocket')
          // 创建websocket对象，指定要链接的服务器地址和端口，建立连接
          var socketUrl = `http://localhost:8091/websocket/${this.userId}`
          socketUrl = socketUrl.replace('https', 'ws').replace('http', 'ws')
          // 如果已经被打开了，先关闭，然后重新创建链接
          if (this.socket != null) {
            this.socket.close()
            this.socket = null
          }
          this.socket = new WebSocket(socketUrl)

          // 打开事件
          this.socket.onopen = function () {
            console.log('webssocket is open!')
          }

          // 获得消息事件
          var that = this
          this.socket.onmessage = function (msg) {
            // this为websocket对象
            console.log('webscoket message :' + msg.data)
            that.receiveMsg = msg.data
          }

          // 关闭事件
          this.socket.onclose = function () {
            console.log('websocket is close!')
          }

          // 发生错误事件
          this.socket.onerror = function () {
            console.log('webscoket occur an error')
          }
          console.log(socketUrl)
        }
      },
      sendMessage () {
        if (typeof (WebSocket) === 'undefined') {
          console.log('your browser not support websocket!')
        } else {
          console.log('your borwserr support websocket!')
          const message = '{"toUserId":"' + this.toUserId + '","contentText":"' + this.contentText + '"}'
          console.log(message)
          this.socket.send(message)
        }
      }
    }
  }
</script>

<style  scoped>
  .wrapper{
    width: 100%;
    height: 100%;
  }
</style>

